package com.example.onewebonedatabase.controller;

import java.time.LocalDateTime;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.onewebonedatabase.entity.Order;
import com.example.onewebonedatabase.service.OrderService;
import com.example.onewebonedatabase.service.TradeService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangwz
 * @create 2019/6/27.
 */
@RequestMapping("trade")
@RestController
@Slf4j
public class TradeController implements CommandLineRunner {

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    OrderService orderService;
    @Autowired
    TradeService tradeService;
    @Autowired
    RedissonClient redissonClient;


    @GetMapping("/test")
    public Object test(){
        String k = "k---1";
        redisTemplate.opsForValue().set(k, "1000");
        Long decrement = redisTemplate.opsForValue().decrement(k, 1);
        System.out.println(decrement);
        return "ok";
    }

    @Override
    public void run(String... args) throws Exception {
        String k = "k-1";
        redisTemplate.opsForValue().set(k, "1000");
        orderService.deleteAll();
    }


    /**
     * 基于redis不会超卖
     * @param id
     * @return
     */
    @GetMapping("/buy/{id}")
    public Object buyTrade2(@PathVariable("id") Long id){
        String key = "k-"+id;
        Long decrement = redisTemplate.opsForValue().decrement(key, 1);
        if (decrement > -1) {
            log.info("剩余个数 ：" + decrement);
            Order order = new Order();
            order.setCreateDate(LocalDateTime.now());
            order.setUserId((long) new Random().nextInt(2000));
            orderService.save(order);
        }
        return "ok";
    }

    @GetMapping("/testRedis")
    public Object testRedis(){
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String temp = opsForValue.get("temp");
        if (StringUtils.isBlank(temp)) {
            temp = "1";
        }
        System.out.println(temp);
        opsForValue.set("temp", (Integer.parseInt(temp) + 1) + "");
        lock.unlock();
        return "ok";
    }
}
